//
//  SEGOrderMessageViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/8.
//

#import "SEGOrderMessageViewModel.h"
#import "MessageRequestModel.h"
#import "MessageDataBaseModel.h"

@interface SEGOrderMessageViewModel ()

@end

@implementation SEGOrderMessageViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createMsgV3Command];
        [self seg_createProviderCommand];
        [self seg_createReceiveCommand];
        [self seg_createUpLoadImgCommand];
        [self seg_createSendMsgCommand];
    }
    return self;
}

- (void)seg_createMsgV3Command {
    @weakify(self);
    self.msgV3Command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *groupID) {
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[MessageRequestModel sharedRequestModel] requestMessageList:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                self.resultArray = [[NSMutableArray alloc] initWithArray:[[MessageDataBaseModel sharedDataBaseModel] getMessageWithGroupId:groupID]];
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}
- (void)seg_createProviderCommand {
    @weakify(self);
    self.providerCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *groupID) {
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[MessageRequestModel sharedRequestModel] requestProviderDetailWithProviderSid:[groupID componentsSeparatedByString:@"|"][1] finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage)  {
                NSString *title;
                if (isSuccessed) {
                    NSDictionary *dict = result;
                    if ( [codeType isEqualToString:@"0"]) {
                        self.tel = [NSString stringWithFormat:@"%@", [[[dict objectForKey:@"data"] objectForKey:@"providerInfo"] objectForKey:@"contactPhone"]];
                        self.headerImageUrl = [NSString stringWithFormat:@"%@", [[[dict objectForKey:@"data"] objectForKey:@"providerInfo"] objectForKey:@"brandLogo"]];
                        self.providerName = [NSString stringWithFormat:@"%@", [[[dict objectForKey:@"data"] objectForKey:@"providerInfo"] objectForKey:@"name"]];
                        title = [[[dict objectForKey:@"data"] objectForKey:@"providerInfo"] objectForKey:@"brandName"];
                    }
                }
                [subscriber sendNext:title];
                [subscriber sendCompleted];
            }];
            
            return nil;
        }];
    }];
}
- (void)seg_createReceiveCommand {
    @weakify(self);
    self.receiveCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *groupID) {
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[MessageRequestModel sharedRequestModel] requestMessageList:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    // 消息及时刷新
                    self.resultArray = [[NSMutableArray alloc] initWithArray:[[MessageDataBaseModel sharedDataBaseModel] getMessageWithGroupId:groupID]];
                    // 修改这个页面上的所有消息为已读 防止在本页读消息时收到新消息返回消息中心时新消息仍为未读
                    [[MessageDataBaseModel sharedDataBaseModel] updateMessagesToReadInDataBaseWithGroupId:groupID];
                }
                
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            }];
             
            return nil;
        }];
    }];
}
- (void)seg_createUpLoadImgCommand {
    self.upLoadImgCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSArray<UIImage *> *photos) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            NSMutableArray *upLoadImages = [NSMutableArray array];
            [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [upLoadImages addObject:obj];
            }];
            if (upLoadImages.count > 0) {
                [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:upLoadImages progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        NSArray *data = result[@"data"];
                        [subscriber sendNext:data];
                        [subscriber sendCompleted];
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:@"图片发送失败，请检查网络"}];
                        [subscriber sendError:error];
                    }
                }];
            }
             
            return nil;
        }];
    }];
}
- (void)seg_createSendMsgCommand {
    @weakify(self);
    self.sendMsgCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(RACTuple *tuple) {
        RACTupleUnpack(NSDictionary *dic, NSString *groupID) = tuple;
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[MessageRequestModel sharedRequestModel] requestPushMessageWithParamsDict:dic finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    MessageModel *message = [[MessageModel alloc] init];
                    [message setTitle:self.headerImageUrl]; // 消息标题
                    [message setMessage:dic[@"description"]]; // 消息内容
                    [message setGroupid:groupID]; // 组id
                    [message setSender:kAccountNickName]; // 发送者
                    [message setType:kMessageTypeHomeService]; // 模块自定义id
                    [message setUuid:kAccountUserID]; // 登陆用户id
                    [message setContenttype:dic[@"contentType"]]; // 类容类型定义:1为文本，2为图片，3为语音，4为视频 5 借条
                    [message setSendUserId:kAccountUserID];
                    [message setCommunityId:kAccountCommunityID];
                    message.createTime = [SEGUtils stringDateByFormatString:@"yyyy-MM-dd HH:mm" withDate:[NSDate date]];
                    message.isRead = @"1";
                    
                    [self.resultArray addObject:message];
                    [[MessageDataBaseModel sharedDataBaseModel] saveMessageWithModel:message];
                    
                    [subscriber sendNext:@""];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            
            return nil;
        }];
    }];
}

@end
